package be.ipl.pigolo.servlets;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.pigolo.domaine.Partie;
import be.ipl.pigolo.usecases.GestionPartie;
import be.ipl.pigolo.util.Util;

/**
 * Servlet implementation class liste des journaux
 * 
 * @author lspitaels,sdoublier
 */
@WebServlet(name = "listedesjournaux.html")
public class ListeDesJournaux extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	GestionPartie gestPartie;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = "";
		gestPartie = null;

		synchronized (session) {
			username = (String) session.getAttribute("fermier");
			gestPartie = (GestionPartie) session.getAttribute("gestionpartie");
		}

		if (Util.checkNullEmpty(username)) {
			String erreurSession = "Merci de vous connecter au préalable.";
			response.sendRedirect(response
					.encodeRedirectURL("accueil.html?erreurSession="
							+ erreurSession));
		} else {
			try {
				List<Partie> listeDesParties = gestPartie
						.listerToutesLesParties();
				if (listeDesParties != null) {
					request.setAttribute("toutesLesParties", listeDesParties);
					request.setAttribute("nombreTotalParties",
							listeDesParties.size());
				}
			} catch (Exception e) {
				request.setAttribute("message", e.getMessage());
			}
			getServletContext().getNamedDispatcher("listejournaux.html")
					.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = "";
		gestPartie = null;

		synchronized (session) {
			username = (String) session.getAttribute("fermier");
			gestPartie = (GestionPartie) session.getAttribute("gestionpartie");
		}

		if (Util.checkNullEmpty(username)) {
			String erreurSession = "Merci de vous connecter au préalable.";
			response.sendRedirect(response
					.encodeRedirectURL("accueil.html?erreurSession="
							+ erreurSession));
		} else {
			String nomPartie = (String) request.getParameter("nomPartie");

			request.setAttribute("journal", gestPartie.journal(nomPartie));
			getServletContext().getNamedDispatcher("affichejournal.html")
					.forward(request, response);
		}
	}

}
